package com.fencing_squad.homo.slice;

import com.alibaba.fastjson.JSONObject;
import com.bumptech.glide.Glide;
import com.fencing_squad.homo.ResourceTable;
import com.fencing_squad.homo.list.Offer;
import com.fencing_squad.homo.map_util.bean.InputTipsResult;
import com.fencing_squad.homo.map_util.map.MapDataHelper;
import com.fencing_squad.homo.map_util.map.MapElement;
import com.fencing_squad.homo.map_util.map.MapManager;
import com.fencing_squad.homo.map_util.map.NavMap;
import com.fencing_squad.homo.util.AnimationConfig;
import com.fencing_squad.homo.util.CustomComponent;
import com.fencing_squad.homo.util.ImageLoader;
import com.fencing_squad.homo.util.Network;
import ohos.aafwk.ability.AbilitySlice;
import ohos.aafwk.content.Intent;
import ohos.agp.components.*;
import ohos.multimodalinput.event.TouchEvent;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class SupervisorSlice extends AbilitySlice {
    private MapDataHelper mapDataHelper;
    
    private MapManager mapManager;
    
    private NavMap navMap;
    
    private String rewardId;
    
    private boolean isSupervisor;
    
    private Offer offer;
    
    private Text content;
    
    private Image img;
    
    private Text toDetail;
    
    private Text fromDetail;
    
    private Text type;
    
    private Text level;
    
    private Text reward;
    
    private boolean fold =true;

    private boolean isStart = false;

    @Override
    protected void onStart(Intent intent) {
        super.onStart(intent);
        super.setUIContent((ComponentContainer) LayoutScatter.getInstance(this).parse(ResourceTable.Layout_supervisor, null, false));

        rewardId = intent.getStringParam("rewardId");
        isSupervisor = intent.getBooleanParam("isSupervisor", false);
        if (rewardId == null) {
            terminate();
            return;
        }

        initConfig();
    }

    @Override
    protected void onStop() {
        super.onStop();
        mapManager.endNav();
    }

    private void initConfig() {
        Text barTitle = (Text) findComponentById(ResourceTable.Id_barTitle);
        Component barBack = findComponentById(ResourceTable.Id_barBack);
        barTitle.setText("悬赏详情");
        barBack.setClickedListener(component -> {
            terminate();
        });

        Component offerInfo = findComponentById(ResourceTable.Id_offerInfo);
        final int[] initial = {0, 0};
        VelocityDetector detector = VelocityDetector.obtainInstance();
        offerInfo.setTouchEventListener(new Component.TouchEventListener() {
            @Override
            public boolean onTouchEvent(Component component, TouchEvent touchEvent) {
                int top = offerInfo.getTop();
                int index = touchEvent.getIndex();
                int y = (int) touchEvent.getPointerScreenPosition(index).getY();
                detector.addEvent(touchEvent);
                if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_DOWN) {
                    if (index == -1) {
                        return true;
                    }
                    initial[1] = initial[0] = y;
                }
                else if (touchEvent.getAction() == TouchEvent.POINT_MOVE) {
                    if(index != -1) {
                        int delta = y - initial[1];
                        if (top >= vp2px(620) && delta > 0) {
                            return true;
                        }
                        else if (top <= vp2px(190) && delta < 0) {
                            return true;
                        }
                        offerInfo.setTop(offerInfo.getTop() + y - initial[1]);
                        initial[1] = y;
                    }
                }
                else if (touchEvent.getAction() == TouchEvent.PRIMARY_POINT_UP) {
                    detector.calculateCurrentVelocity(1000, 22000, 22000);
                    int speed = (int) detector.getVerticalVelocity();//获得当前的滑动速度
                    int delta = y - initial[0];//获取手指滑动距离
                    if ( top < vp2px(190) || fold && (speed > 1200 || delta < -300) || !fold && (speed <= 1200 && delta <= 300)) {
                        AnimationConfig.getOfferInfoShowAnim(offerInfo).start();
                        fold = false;
                    }
                    else if ( top > vp2px(620) || !fold && (speed > 1200 || delta > 300) || fold && (speed <= 1200 && delta >= -300)) {
                        AnimationConfig.getOfferInfoHideAnim(offerInfo).start();
                        fold = true;
                    }
                }
                return true;
            }
        });
        
        content = (Text) findComponentById(ResourceTable.Id_content);
        img = (Image) findComponentById(ResourceTable.Id_image);
        toDetail = (Text) findComponentById(ResourceTable.Id_toDetail);
        fromDetail = (Text) findComponentById(ResourceTable.Id_fromDetail);
        type = (Text) findComponentById(ResourceTable.Id_type);
        level = (Text) findComponentById(ResourceTable.Id_level);
        reward = (Text) findComponentById(ResourceTable.Id_reward);
        Button startNav = (Button) findComponentById(ResourceTable.Id_startNav);
        Component checkDetail = findComponentById(ResourceTable.Id_checkDetail);

        navMap = (NavMap) findComponentById(ResourceTable.Id_map);
        navMap.setDrawPath(true);
        mapDataHelper = new MapDataHelper(navMap, this);
        mapManager = new MapManager(navMap, this);

        if (isSupervisor) {
            startNav.setVisibility(Component.HIDE);
        }

        startNav.setClickedListener(component -> {
            if (offer == null) {
                return;
            }
            if (mapManager != null && !isStart) {
                mapManager.startNav();
                startNav.setText("结束导航");
                isStart = true;
            }
            else if (mapManager != null && isStart) {
                mapManager.endNav();
                startNav.setText("开始导航");
                isStart = false;
            }
        });

        checkDetail.setClickedListener(component -> {
            if (fold) {
                AnimationConfig.getOfferInfoShowAnim(offerInfo).start();
                fold = false;
            }
        });

        mapDataHelper.setDataCallBack(new MapDataHelper.DataCallBack() {
            @Override
            public void setInputTipsView(List<InputTipsResult.TipsEntity> tips) {}

            @Override
            public void setRouteView(String route) {
                setRoute(route);
            }
        });

        Map<String, String> params = new ConcurrentHashMap<>();
        params.put("reward_id", rewardId);
        Network.get("/reward/detail", params, this::resolve, this::reject);

        mapManager.setNavListener(mapElement -> {
            navMap.setCenterPoint(mapElement.getMercatorPoint(), -1);
        });
    }

    private void resolve(JSONObject object) {

        offer = new Offer(object.getJSONObject("data"));
        mapDataHelper.getRouteResult(offer.getFromPos(), offer.getToPos());

        content.setText(offer.getContent());
        toDetail.setText(offer.getToDetail());
        fromDetail.setText(offer.getFromDetail());
        type.setText(offer.getType());
        level.setText(offer.getLevel());
        reward.setText(offer.getReward());
        if (!offer.getImg().equals("")) {
            img.setVisibility(Component.VISIBLE);
            Glide.with(this).load(offer.getImg()).listener(ImageLoader.fail(img, ResourceTable.Media_icon)).into(img);
        }
    }

    private void reject(int code, String message) {
        if(code == 404) {
            CustomComponent.getDialog(this, message, null, null).show();
        }
        else {
            System.out.println(message);
        }
    }

    private void setRoute(String route) {
        if (mapDataHelper != null) {
            try {
                mapDataHelper.parseRoute(route);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private int vp2px(float vp) {
        return AttrHelper.vp2px(vp, this);
    }
}
